﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using MyGIS.Classes;
using MyGIS.Forms;
using ESRI.ArcGIS.esriSystem;
using static System.Windows.Forms.Cursor;
using static System.Windows.Forms.Cursors;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.SpatialAnalyst;
using ESRI.ArcGIS.GeoAnalyst;
using System.IO;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.Geoprocessing;
using System.Diagnostics;
using ESRI.ArcGIS.Output;
using System.Runtime.InteropServices;
using Path = System.IO.Path;

namespace MyGIS
{
    public partial class Form1 : Form
    {

        private System.Timers.Timer autoUpdateTimer;
        private bool isAutoUpdating = false;
        private int mLayerIndex;
        private ContextMenuStrip tocContextMenu = new ContextMenuStrip();
        private Pan mPan;
        private ZoomOut mZoomOut;
        private FixedZoomIn mFixedZoomIn;
        private FixedZoomOut mFixedZoomOut;
        private string mTool;//
        private ZoomIn mZoomIn;
        //空间查询的查询方式
        private int mQueryMode;
        //图层索引


        public Form1()
        {
            InitializeComponent();
            mPan = new Pan();
            mZoomIn = new ZoomIn();
            mZoomOut = new ZoomOut();
            mFixedZoomIn = new FixedZoomIn();
            mFixedZoomOut = new FixedZoomOut();

        }
        //
        public void UpdateDataGridView(DataTable data)
        {
            this.dataGridView1.DataSource = data;
            this.dataGridView1.Refresh();
        }
        //


        private void axMapControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e)
        {

        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripContainer1_ContentPanel_Load(object sender, EventArgs e)
        {

        }

        private void splitContainer2_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void splitContainer2_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void menuFileOpen_Click(object sender, EventArgs e)
        {
            //文件路径名称,包含文件名称和路径名称
            string strName = null;

            //定义OpenFileDialog，获取并打开地图文档
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "打开MXD";
            openFileDialog.Filter = "MXD文件（*.mxd）|*.mxd";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                strName = openFileDialog.FileName;
                if (strName != "")
                {
                    this.axMapControl1.LoadMxFile(strName);
                }
            }
            //地图文档全图显示
            this.axMapControl1.Extent = this.axMapControl1.FullExtent;
        }

        private void 添加数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ICommand cmd = new ControlsAddDataCommandClass();
            cmd.OnCreate(this.axMapControl1.Object);
            cmd.OnClick();
        }

        private void menuExit_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void menuFullExtent_Click(object sender, EventArgs e)
        {
            //初始化FullExtent对象
            FullExtent fullExtent = new FullExtent();
            //FullExtent对象与MapControl关联
            fullExtent.OnCreate(this.axMapControl1.Object);
            fullExtent.OnClick();
        }

        private void menuZoomIn_Click(object sender, EventArgs e)
        {
            toolZoomIn_Click(sender, e);
        }
        private void menuZoomOut_Click(object sender, EventArgs e)
        {
            toolZoomOut_Click(sender, e);
        }
        private void menuFixedZoomIn_Click(object sender, EventArgs e)
        {
            toolFixedZoomIn_Click(sender, e);
        }

        private void menuFixedZoomOut_Click(object sender, EventArgs e)
        {
            toolFixedZoomOut_Click(sender, e);
        }
        private void menuPan_Click(object sender, EventArgs e)
        {
            //初始化Pan对象
            mPan = new Pan();
            //Pan对象与MapControl关联
            mPan.OnCreate(this.axMapControl1.Object);
            //设置鼠标形状
            this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerPan;
            //标记操作为“Pan”
            this.mTool = "Pan";
        }

        private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
        {

        }

        private void axMapControl1_OnMouseDown_1(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            this.axMapControl1.Map.ClearSelection();
            //获取当前视图
            IActiveView pActiveView = this.axMapControl1.ActiveView;
            //获取鼠标点
            IPoint pPoint = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
            switch (mTool)
            {
                case "ZoomIn":
                    this.mZoomIn.OnMouseDown(e.button, e.shift, e.x, e.y);
                    break;
                case "ZoomOut":
                    this.mZoomOut.OnMouseDown(e.button, e.shift, e.x, e.y);
                    break;
                case "Pan":
                    //设置鼠标形状
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerPanning;
                    this.mPan.OnMouseDown(e.button, e.shift, e.x, e.y);
                    break;
                case "SpaceQuery":
                    IGeometry pGeometry = null;
                    if (this.mQueryMode == 0)//矩形查询
                    {
                        pGeometry = this.axMapControl1.TrackRectangle();
                    }
                    else if (this.mQueryMode == 1)//线查询
                    {
                        pGeometry = this.axMapControl1.TrackLine();
                    }
                    else if (this.mQueryMode == 2)//点查询
                    {
                        ITopologicalOperator pTopo;
                        IGeometry pBuffer;
                        pGeometry = pPoint;
                        pTopo = pGeometry as ITopologicalOperator;
                        //根据点位创建缓冲区，缓冲半径为0.1，可修改
                        pBuffer = pTopo.Buffer(0.1);
                        pGeometry = pBuffer.Envelope;
                    }
                    else if (this.mQueryMode == 3)//圆查询
                    {
                        pGeometry = this.axMapControl1.TrackCircle();
                    }
                    IFeatureLayer pFeatureLayer = this.axMapControl1.get_Layer(this.mLayerIndex) as IFeatureLayer;
                    DataTable pDataTable = this.LoadQueryResult(this.axMapControl1, pFeatureLayer, pGeometry);
                    this.dataGridView1.DataSource = pDataTable.DefaultView;

                    this.dataGridView1.Refresh();
                    break;
                default:
                    break;
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            switch (mTool)
            {
                case "ZoomIn":
                    this.mZoomIn.OnMouseMove(e.button, e.shift, e.x, e.y);
                    break;
                case "ZoomOut":
                    // 确保只传递鼠标移动事件给当前活动工具
                    if (this.axMapControl1.CurrentTool is ZoomOut)
                    {
                        this.mZoomOut.OnMouseMove(e.button, e.shift, e.x, e.y);
                    }
                    break;
                case "Pan":
                    this.mPan.OnMouseMove(e.button, e.shift, e.x, e.y);
                    break;
                default:
                    break;
            }
            // 显示当前比例尺
            this.StatusScale.Text = " 比例尺 1:" + ((long)this.axMapControl1.MapScale).ToString();
            //// 显示当前坐标
            this.StatusCoordinate.Text = " 当前坐标 X = " + e.mapX.ToString() + " Y = " + e.mapY.ToString() + " " + this.axMapControl1.MapUnits;
            //this.statueCoordinate.Text = $" 当前坐标 X = {e.mapX} Y = {e.mapY} {this.axMapControl1.MapUnits}";

        }


        private void axMapControl1_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e)
        {
            switch (mTool)
            {
                case "ZoomIn":
                    this.mZoomIn.OnMouseMove(e.button, e.shift, e.x, e.y);
                    break;
                case "ZoomOut":
                    this.mZoomOut.OnMouseMove(e.button, e.shift, e.x, e.y);
                    break;
                case "Pan":
                    this.mPan.OnMouseUp(e.button, e.shift, e.x, e.y);
                    //设置鼠标形状
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerPan;
                    break;
                default:
                    break;
            }
        }

        private void menuAttributeQuery_Click(object sender, EventArgs e)
        {
            ////初始化属性查询窗体
            //AttributeQueryForm attributeQueryForm = new AttributeQueryForm(this.axMapControl1);
            //attributeQueryForm.Show();
            //初始化属性查询窗体
            using (AttributeQueryForm attributeQueryForm = new AttributeQueryForm(this.axMapControl1))
            {
                attributeQueryForm.Owner = this;
                attributeQueryForm.ShowDialog();
            }
        }
        private DataTable LoadQueryResult(AxMapControl mapControl, IFeatureLayer featureLayer, IGeometry geometry)
        {
            IFeatureClass pFeatureClass = featureLayer.FeatureClass;

            //根据图层属性字段初始化DataTable
            IFields pFields = pFeatureClass.Fields;
            DataTable pDataTable = new DataTable();
            for (int i = 0; i < pFields.FieldCount; i++)//i->i++
            {
                string strFldName;
                strFldName = pFields.get_Field(i).AliasName;
                pDataTable.Columns.Add(strFldName);
            }

            //空间过滤器
            ISpatialFilter pSpatialFilter = new SpatialFilter();
            pSpatialFilter.Geometry = geometry;

            //根据图层类型选择缓冲方式
            switch (pFeatureClass.ShapeType)
            {
                case esriGeometryType.esriGeometryPoint:
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses;
                    break;
                case esriGeometryType.esriGeometryPolygon:
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    break;
            }
            //定义空间过滤器的空间字段
            pSpatialFilter.GeometryField = pFeatureClass.ShapeFieldName;

            IQueryFilter pQueryFilter;
            IFeatureCursor pFeatureCursor;
            IFeature pFeature;
            //利用要素过滤器查询要素
            pQueryFilter = pSpatialFilter as IQueryFilter;
            pFeatureCursor = featureLayer.Search(pQueryFilter, true);
            pFeature = pFeatureCursor.NextFeature();

            while (pFeature != null)
            {
                string strFldValue = null;
                DataRow dr = pDataTable.NewRow();
                //遍历图层属性表字段值，并加入pDataTable
                for (int i = 0; i < pFields.FieldCount; i++)//i->i++
                {
                    string strFldName = pFields.get_Field(i).Name;
                    if (strFldName == "Shape")
                    {
                        strFldValue = Convert.ToString(pFeature.Shape.GeometryType);
                    }
                    else
                        strFldValue = Convert.ToString(pFeature.get_Value(i));
                    dr[i] = strFldValue;
                }
                pDataTable.Rows.Add(dr);
                //高亮选择要素
                mapControl.Map.SelectFeature((ILayer)featureLayer, pFeature);
                mapControl.ActiveView.Refresh();
                pFeature = pFeatureCursor.NextFeature();
            }
            return pDataTable;
        }

        private void menuSpatialQuery_Click(object sender, EventArgs e)
        {
            //初始化空间查询窗体
            SpatialQueryForm spatialQueryForm = new SpatialQueryForm(this.axMapControl1);
            if (spatialQueryForm.ShowDialog() == DialogResult.OK)
            {
                //标记为“空间查询”
                this.mTool = "SpaceQuery";
                //获取查询方式和图层
                this.mQueryMode = spatialQueryForm.mQueryMode;
                this.mLayerIndex = spatialQueryForm.mLayerIndex;
                //定义鼠标形状
                this.axMapControl1.MousePointer = ESRI.ArcGIS.Controls.esriControlsMousePointer.esriPointerCrosshair;
            }
        }

        private void toolFullExtent_Click(object sender, EventArgs e)
        {
            //初始化FullExtent对象
            ICommand cmd = new ControlsMapFullExtentCommandClass();
            //FullExtent与MapControl的关联
            cmd.OnCreate(this.axMapControl1.Object);
            cmd.OnClick();
        }

        private void toolPan_Click(object sender, EventArgs e)
        {
            //初始化Pan对象
            ITool tool = new ControlsMapPanToolClass();
            //查询接口，初试化Command类型
            ICommand cmd = tool as ICommand;
            //Command与MapControl的关联
            cmd.OnCreate(this.axMapControl1.Object);
            cmd.OnClick();
            //当前MapControl的工具设为Pan
            this.axMapControl1.CurrentTool = tool;
        }

        private void UpdateToolbarIcons()
        {

            toolZoomIn.Checked = (mTool == "ZoomIn");
            toolZoomOut.Checked = (mTool == "ZoomOut");
            toolFixedZoomIn.Checked = (mTool == "FixedZoomIn");
            toolFixedZoomOut.Checked = (mTool == "FixedZoomOut");

        }
        private void toolZoomIn_Click(object sender, EventArgs e)
        {

            mZoomIn = new ZoomIn();
            mZoomIn.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = mZoomIn as ITool;
            this.mTool = "ZoomIn";
            UpdateToolbarIcons();
            this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
        }

        private void toolZoomOut_Click(object sender, EventArgs e)
        {

            mZoomOut = new ZoomOut();
            mZoomOut.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = mZoomOut as ITool;
            this.mTool = "ZoomOut";
            UpdateToolbarIcons();
            this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
        }
        private void toolFixedZoomIn_Click(object sender, EventArgs e)
        {
            mFixedZoomIn = new FixedZoomIn();
            mFixedZoomIn.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = null; // 固定缩放工具不需要设置CurrentTool
            mFixedZoomIn.OnClick();
            this.mTool = "FixedZoomIn";
            UpdateToolbarIcons();


        }

        private void toolFixedZoomOut_Click(object sender, EventArgs e)
        {
            mFixedZoomOut = new FixedZoomOut();
            mFixedZoomOut.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = null; // 固定缩放工具不需要设置CurrentTool
            mFixedZoomOut.OnClick();
            this.mTool = "FixedZoomOut";
            UpdateToolbarIcons();
        }

        private async void 加载实时数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string url = "https://eolink.o.apispace.com/34324/air/v001/aqi?areacode=101090501";
                string token = "qihmwk7zymt60fkwbpmdym83aho0oq6s";

                // 添加等待提示
                Current = WaitCursor;
                加载实时数据ToolStripMenuItem.Enabled = false;

                // 异步获取数据
                List<AirStation> stations = await ApiClient.GetStationsAsync(url, token);

                if (stations == null || stations.Count == 0)
                {
                    MessageBox.Show("数据为空或获取失败，请检查接口返回内容！");
                    return;
                }

                // 处理数据
                DrawStations(stations);
                LoadStationsToFeatureLayer(stations);
            }
            catch (Exception ex)
            {
                MessageBox.Show("接口调用失败：" + ex.Message);
            }
            finally
            {
                // 恢复UI状态
                Current = Default;
                加载实时数据ToolStripMenuItem.Enabled = true;
            }
        }



        private void Form1_Load(object sender, EventArgs e)
        {
            cmbPollutant.Items.AddRange(new string[] { "aqi", "pm25", "pm10", "no2", "so2", "co", "o3" });
            cmbPollutant.SelectedIndex = 0; // 默认显示 AQI
        }
        private double GetPollutantValue(AirStation station, string type)
        {
            switch (type.ToLower())
            {
                case "aqi": return station.aqi;
                case "pm25": return station.pm25;
                case "pm10": return station.pm10;
                case "no2": return station.no2;
                case "so2": return station.so2;
                case "co": return station.co;
                case "o3": return station.o3;
                default: return 0;
            }
        }

        private void DrawStations(List<AirStation> stations)
        {
            string selectedPollutant = cmbPollutant.SelectedItem.ToString(); // 选中的污染物

            IGraphicsContainer graphicsContainer = axMapControl1.ActiveView.GraphicsContainer;
            graphicsContainer.DeleteAllElements();

            foreach (var station in stations)
            {
                double value = GetPollutantValue(station, selectedPollutant);
                IColor color = SymbolHelper.GetColorByPollutant(selectedPollutant, value);
                ISimpleMarkerSymbol symbol = SymbolHelper.CreatePollutionSymbol(8, color);

                IPoint pt = new PointClass { X = station.lon, Y = station.lat };
                IMarkerElement markerElement = new MarkerElementClass();
                markerElement.Symbol = symbol;
                ((IElement)markerElement).Geometry = pt;

                graphicsContainer.AddElement((IElement)markerElement, 0);
            }

            axMapControl1.ActiveView.Refresh();
        }
        private void RemoveLayerByName(string layerName)
        {
            for (int i = axMapControl1.Map.LayerCount - 1; i >= 0; i--)
            {
                ILayer layer = axMapControl1.Map.get_Layer(i);
                if (layer.Name == layerName)
                {
                    axMapControl1.Map.DeleteLayer(layer);
                }
            }
        }


        public void LoadStationsToFeatureLayer(List<AirStation> stations)
        {
            RemoveLayerByName("污染站点图层");
            try
            {
                // 创建字段集合
                IFields fields = new FieldsClass();
                IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

                // 添加 Shape 字段
                IField shapeField = new FieldClass();
                IFieldEdit shapeFieldEdit = (IFieldEdit)shapeField;
                shapeFieldEdit.Name_2 = "Shape";
                shapeFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

                // 定义 Geometry
                IGeometryDef geometryDef = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;

                ISpatialReference spatialRef = axMapControl1.SpatialReference;
                if (spatialRef == null)
                {
                    ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();
                    spatialRef = srFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
                }
                geometryDefEdit.SpatialReference_2 = spatialRef;
                shapeFieldEdit.GeometryDef_2 = geometryDef;
                fieldsEdit.AddField(shapeField);

                // 添加属性字段
                AddTextField(fieldsEdit, "stationId", 20);
                AddTextField(fieldsEdit, "name", 50);
                AddDoubleField(fieldsEdit, "lon");
                AddDoubleField(fieldsEdit, "lat");
                AddIntegerField(fieldsEdit, "aqi");
                AddDoubleField(fieldsEdit, "pm25");
                AddDoubleField(fieldsEdit, "pm10");
                AddDoubleField(fieldsEdit, "no2");
                AddDoubleField(fieldsEdit, "so2");
                AddDoubleField(fieldsEdit, "co");
                AddDoubleField(fieldsEdit, "o3");
                AddTextField(fieldsEdit, "aqi_level", 20);

                // 创建内存工作空间
                IWorkspaceFactory workspaceFactory = new InMemoryWorkspaceFactoryClass();
                IWorkspaceName workspaceName = workspaceFactory.Create("", "TempMemWS", null, 0);
                IName name = (IName)workspaceName;
                IWorkspace workspace = (IWorkspace)name.Open();

                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;

                // 创建要素类
                IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(
                    "AirStations",
                    fields, null, null,
                    esriFeatureType.esriFTSimple,
                    "Shape", "");

                // 插入数据
                foreach (var station in stations)
                {
                    IFeature feature = featureClass.CreateFeature();
                    IPoint point = new PointClass { X = station.lon, Y = station.lat };
                    point.SpatialReference = spatialRef;
                    feature.Shape = point;

                    feature.set_Value(feature.Fields.FindField("stationId"), station.stationId);
                    feature.set_Value(feature.Fields.FindField("name"), station.name);
                    feature.set_Value(feature.Fields.FindField("lon"), station.lon);
                    feature.set_Value(feature.Fields.FindField("lat"), station.lat);
                    feature.set_Value(feature.Fields.FindField("aqi"), station.aqi);
                    feature.set_Value(feature.Fields.FindField("pm25"), station.pm25);
                    feature.set_Value(feature.Fields.FindField("pm10"), station.pm10);
                    feature.set_Value(feature.Fields.FindField("no2"), station.no2);
                    feature.set_Value(feature.Fields.FindField("so2"), station.so2);
                    feature.set_Value(feature.Fields.FindField("co"), station.co);
                    feature.set_Value(feature.Fields.FindField("o3"), station.o3);
                    feature.set_Value(feature.Fields.FindField("aqi_level"), station.aqi_level);
                    feature.Store();
                }

                // 加载到地图中
                IFeatureLayer featureLayer = new FeatureLayerClass
                {
                    FeatureClass = featureClass,
                    Name = "污染站点图层"
                };

                axMapControl1.Map.AddLayer((ILayer)featureLayer);
                axMapControl1.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show("创建图层失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void AddTextField(IFieldsEdit fieldsEdit, string name, int length)
        {
            IField field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = name;
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit.Length_2 = length;
            fieldsEdit.AddField(field);
        }

        private void AddDoubleField(IFieldsEdit fieldsEdit, string name)
        {
            IField field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = name;
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
            fieldsEdit.AddField(field);
        }

        private void AddIntegerField(IFieldsEdit fieldsEdit, string name)
        {
            IField field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = name;
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            fieldsEdit.AddField(field);
        }

        private void cmbPollutant_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private async void 手动更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string url = "https://eolink.o.apispace.com/34324/air/v001/aqi?areacode=101090501";
                string token = "qihmwk7zymt60fkwbpmdym83aho0oq6s";

                // 添加等待提示
                Current = WaitCursor;
                手动更新ToolStripMenuItem.Enabled = false;

                // 异步获取数据
                List<AirStation> stations = await ApiClient.GetStationsAsync(url, token);

                if (stations == null || stations.Count == 0)
                {
                    MessageBox.Show("数据为空或获取失败，请检查接口返回内容！");
                    return;
                }

                // 处理数据
                DrawStations(stations);
                LoadStationsToFeatureLayer(stations);
            }
            catch (Exception ex)
            {
                MessageBox.Show("接口调用失败：" + ex.Message);
            }
            finally
            {
                // 恢复UI状态
                Current = Default;
                手动更新ToolStripMenuItem.Enabled = true;
            }
        }

        private void 自动更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (isAutoUpdating)
            {
                // 如果正在自动更新，则停止
                StopAutoUpdate();
                自动更新ToolStripMenuItem.Text = "开始自动更新";
            }
            else
            {
                // 如果未在自动更新，则启动
                StartAutoUpdate();
                自动更新ToolStripMenuItem.Text = "停止自动更新";
            }
        }
        private void StartAutoUpdate()
        {
            if (autoUpdateTimer == null)
            {
                autoUpdateTimer = new System.Timers.Timer(30000); // 30秒间隔
                autoUpdateTimer.Elapsed += async (sender, e) => await AutoUpdateDataAsync();
                autoUpdateTimer.AutoReset = true;
            }

            autoUpdateTimer.Start();
            isAutoUpdating = true;

            // 立即执行一次更新
            _ = AutoUpdateDataAsync();
        }

        private void StopAutoUpdate()
        {
            if (autoUpdateTimer != null)
            {
                autoUpdateTimer.Stop();
            }
            isAutoUpdating = false;
        }

        private async Task AutoUpdateDataAsync()
        {
            // 确保在主线程上更新UI
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(async () => await AutoUpdateDataAsync()));
                return;
            }

            try
            {
                string url = "https://eolink.o.apispace.com/34324/air/v001/aqi?areacode=101090501";
                string token = "qihmwk7zymt60fkwbpmdym83aho0oq6s";

                // 添加等待提示
                Current = WaitCursor;
                自动更新ToolStripMenuItem.Enabled = false;

                // 异步获取数据
                List<AirStation> stations = await ApiClient.GetStationsAsync(url, token);

                if (stations == null || stations.Count == 0)
                {
                    MessageBox.Show("数据为空或获取失败，请检查接口返回内容！");
                    return;
                }

                // 处理数据
                DrawStations(stations);
                LoadStationsToFeatureLayer(stations);
            }
            catch (Exception ex)
            {
                MessageBox.Show("自动更新失败：" + ex.Message);
            }
            finally
            {
                // 恢复UI状态
                Current = Default;
                自动更新ToolStripMenuItem.Enabled = true;
            }
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            StopAutoUpdate(); // 确保窗体关闭时停止定时器
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 检查地图控件中是否有图层
            if (axMapControl1.LayerCount == 0)
            {
                MessageBox.Show("当前地图中没有可保存的图层！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 创建并显示保存窗体
            Save saveForm = new Save(axMapControl1);

            // 以模态对话框形式显示
            saveForm.ShowDialog();
        }

        private void 插值ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // 检查 MapControl 是否已初始化
                if (axMapControl1 == null || axMapControl1.Map == null)
                {
                    MessageBox.Show("请先加载地图数据", "提示",
                                  MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 创建并显示插值窗体
                using (InterpolationForm interpolationForm = new InterpolationForm(axMapControl1))
                {
                    interpolationForm.ShowDialog(); // 使用模态对话框
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开插值窗体时出错: {ex.Message}", "错误",
                              MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        // 修改Idw_Clip方法，增加输出栅格路径参数，返回bool结果
        public bool Idw_Clip(string fieldName, IFeatureLayer pointLayer, IFeatureLayer clipLayer, string outputRaster)
        {
            try
            {
                string pointPath = @"E:\vsm\污染物站点\污染物站点\污染物站点.shp";
                string clipPath = @"E:\vsm\tangshan_prj_web\tangshan_prj_web\tangshan_prj_web.shp";
                string scriptPath = @"E:\vsm\zuoye\interpolate_and_clip.py";

                bool success = RunPythonScript(scriptPath, pointPath, fieldName, outputRaster, clipPath);


                if (!success || !File.Exists(outputRaster))
                    return false;

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("插值裁剪失败：" + ex.Message);
                return false;
            }
        }

        private void 渲染ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var form = new RenderForm(axMapControl1.Map))
            {
                if (form.ShowDialog() == DialogResult.OK && form.SelectedLayer != null)
                {
                    // 确保获取的是栅格图层
                    IRasterLayer sourceLayer = form.SelectedLayer as IRasterLayer;
                    if (sourceLayer == null)
                    {
                        MessageBox.Show("选择的不是有效的栅格图层！");
                        return;
                    }

                    // 创建新的渲染图层
                    IRasterLayer renderedLayer = CreateRenderedLayer(sourceLayer, form.NewLayerName);
                    if (renderedLayer != null)
                    {
                        // 移除同名旧图层
                        RemoveLayerByName(renderedLayer.Name);

                        // 添加新图层并刷新
                        axMapControl1.Map.AddLayer(renderedLayer);
                        axMapControl1.ActiveView.Refresh();
                        axTOCControl1.Update();

                        MessageBox.Show("渲染完成！");
                    }
                }
            }
        }

        private IRasterLayer CreateRenderedLayer(IRasterLayer sourceLayer, string layerName)
        {
            try
            {
                // 创建新栅格图层
                IRasterLayer newLayer = new RasterLayerClass();

                // 直接从源图层复制数据
                newLayer.CreateFromRaster(sourceLayer.Raster);
                newLayer.Name = layerName;

                // 创建热力图渲染器
                IRasterStretchColorRampRenderer renderer = new RasterStretchColorRampRendererClass
                {
                    BandIndex = 0,
                    StretchType = esriRasterStretchTypesEnum.esriRasterStretch_StandardDeviations
                };

                // 设置色带（蓝到红）
                IAlgorithmicColorRamp colorRamp = new AlgorithmicColorRampClass
                {
                    FromColor = CreateRgbColor(0, 0, 255),
                    ToColor = CreateRgbColor(255, 0, 0),
                    Size = 256
                };
                colorRamp.CreateRamp(out bool _);

                renderer.ColorRamp = colorRamp;
                newLayer.Renderer = (IRasterRenderer)renderer;

                // 强制渲染器更新
                ((IRasterRenderer)newLayer.Renderer).Update();

                return newLayer;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建渲染图层失败：{ex.Message}");
                return null;
            }
        }

        private IRasterDataset GetRasterDataset(IRasterLayer layer)
        {
            try
            {
                // 方法1：通过IDataset接口
                if (layer is IDataset dataset)
                {
                    return dataset as IRasterDataset;
                }

                // 方法2：通过Raster属性
                if (layer.Raster is IRasterDataset rasterDataset)
                {
                    return rasterDataset;
                }

                // 方法3：通过RasterBandCollection
                if (layer.Raster is IRasterBandCollection bandCollection && bandCollection.Count > 0)
                {
                    return bandCollection.Item(0).RasterDataset;
                }

                return null;
            }
            catch
            {
                return null;
            }
        }
        private IRasterDataset OpenRasterDataset(string filePath)
        {
            try
            {
                string folder = Path.GetDirectoryName(filePath);
                string name = Path.GetFileName(filePath);

                IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
                IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(folder, 0);
                return rasterWorkspace.OpenRasterDataset(name);
            }
            catch
            {
                return null;
            }
        }

        private void SaveRasterToTemp(IRasterLayer rasterLayer, string tempPath)
        {
            try
            {
                // 获取栅格数据集
                IRasterDataset rasterDataset = GetRasterDataset(rasterLayer);
                if (rasterDataset == null) return;

                // 创建工作空间
                IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
                IWorkspace workspace = workspaceFactory.OpenFromFile(Path.GetDirectoryName(tempPath), 0);

                // 使用 IRasterDataset.Copy 方法保存
                rasterDataset.Copy(Path.GetFileNameWithoutExtension(tempPath), workspace);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存临时文件失败: {ex.Message}");
            }
        }


        // 渲染选定图层的方法
        private void RenderSelectedLayer(ILayer selectedLayer)
        {
            if (selectedLayer is IRasterLayer rasterLayer)
            {
                try
                {
                    // 创建新的渲染器
                    IRasterStretchColorRampRenderer stretchRenderer = new RasterStretchColorRampRendererClass();
                    stretchRenderer.BandIndex = 0;

                    // 设置色带（蓝到红）
                    IAlgorithmicColorRamp colorRamp = new AlgorithmicColorRampClass();
                    colorRamp.FromColor = CreateRgbColor(0, 0, 255); // 蓝色
                    colorRamp.ToColor = CreateRgbColor(255, 0, 0);  // 红色
                    colorRamp.Size = 256;
                    bool ok;
                    colorRamp.CreateRamp(out ok);

                    stretchRenderer.ColorRamp = colorRamp;
                    rasterLayer.Renderer = (IRasterRenderer)stretchRenderer;

                    // 刷新显示
                    axMapControl1.ActiveView.Refresh();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"图层渲染失败：{ex.Message}");
                }
            }
        }
        // 你新写的带参数方法，专门负责生成热力图
        public void GenerateHeatmap(string rasterPath, string fieldName)
        {
            try
            {
                // 加载原始栅格数据集（而不仅仅是栅格）
                IRasterDataset sourceDataset = OpenRasterDataset(rasterPath);
                if (sourceDataset == null)
                {
                    MessageBox.Show("无法加载原始栅格数据集！");
                    return;
                }

                // 使用数据集创建栅格
                IRaster raster = sourceDataset.CreateDefaultRaster();

                // 创建栅格图层
                IRasterLayer heatmapLayer = new RasterLayerClass();
                heatmapLayer.CreateFromRaster(raster);
                heatmapLayer.Name = $"{fieldName}_热力图";

                // 设置热力图渲染器
                IRasterStretchColorRampRenderer renderer = new RasterStretchColorRampRendererClass();
                renderer.BandIndex = 0;

                // 正确设置拉伸类型 - 通过IRasterStretch2接口
                IRasterStretch2 stretch2 = (IRasterStretch2)renderer;
                stretch2.StretchType = esriRasterStretchTypesEnum.esriRasterStretch_StandardDeviations;

                // 创建色带（蓝到红）
                IAlgorithmicColorRamp colorRamp = new AlgorithmicColorRampClass();
                colorRamp.FromColor = CreateRgbColor(0, 0, 255); // 蓝色
                colorRamp.ToColor = CreateRgbColor(255, 0, 0);   // 红色
                colorRamp.Size = 256;
                colorRamp.CreateRamp(out bool _);

                renderer.ColorRamp = colorRamp;
                heatmapLayer.Renderer = (IRasterRenderer)renderer;

                // 强制更新渲染
                IRasterRenderer rasterRenderer = (IRasterRenderer)renderer;
                rasterRenderer.Raster = raster;
                rasterRenderer.Update();

                // 添加到地图前先移除同名图层
                IMap map = axMapControl1.Map;
                for (int i = map.LayerCount - 1; i >= 0; i--)
                {
                    if (map.get_Layer(i).Name.Equals(heatmapLayer.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        map.DeleteLayer(map.get_Layer(i));
                    }
                }

                // 添加到地图并刷新
                map.AddLayer(heatmapLayer);
                axMapControl1.ActiveView.Refresh();
                axTOCControl1.Update();

                MessageBox.Show("热力图生成成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成热力图失败：{ex.Message}\n{ex.StackTrace}");
            }
        }
       
        private bool RunPythonScript(string scriptPath, string pointShp, string fieldName, string outputTif, string clipShp)
        {
            try
            {
                string pythonPath = GetPythonPath();
                if (string.IsNullOrEmpty(pythonPath)) return false;

                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = pythonPath;  // Python解释器路径
                psi.Arguments = $"\"{scriptPath}\" \"{pointShp}\" \"{fieldName}\" \"{outputTif}\" \"{clipShp}\"";
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardError = true;
                psi.UseShellExecute = false;
                psi.CreateNoWindow = true;

                using (Process process = Process.Start(psi))
                {
                    string output = process.StandardOutput.ReadToEnd();
                    string error = process.StandardError.ReadToEnd();
                    process.WaitForExit();

                    File.WriteAllText(@"E:\vsm\zuoye\python_stdout.txt", output);
                    File.WriteAllText(@"E:\vsm\zuoye\python_stderr.txt", error);

                    return process.ExitCode == 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("运行 Python 脚本时出错: " + ex.Message);
                return false;
            }
        }



        private bool ValidatePythonEnvironmentWithDetails(string pythonPath)
        {
            try
            {
                string checkScript = @"
        import sys
        try:
            from osgeo import gdal
            import numpy
            import scipy
            print('GDAL版本:', gdal.__version__)
            print('numpy版本:', numpy.__version__)
            print('scipy版本:', scipy.__version__)
            print('VALID')
        except ImportError as e:
            print('MISSING:', str(e))
            sys.exit(1)
        ";

                string tempFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "py_check.py");
                File.WriteAllText(tempFile, checkScript);

                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = pythonPath,
                        Arguments = $"\"{tempFile}\"",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true
                    }
                };

                StringBuilder output = new StringBuilder();
                process.OutputDataReceived += (sender, args) => output.AppendLine(args.Data);
                process.ErrorDataReceived += (sender, args) => output.AppendLine(args.Data);

                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit(5000);

                string result = output.ToString();
                Console.WriteLine("Python环境验证结果:\n" + result);

                return result.Contains("VALID");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"环境验证异常: {ex.Message}");
                return false;
            }
        }


        // 修正的栅格加载方法
        private IRaster LoadRasterFromFile(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    MessageBox.Show($"文件不存在: {filePath}");
                    return null;
                }

                string folder = System.IO.Path.GetDirectoryName(filePath);
                string name = System.IO.Path.GetFileName(filePath);

                IWorkspaceFactory wsFactory = new RasterWorkspaceFactoryClass();
                IRasterWorkspace rasterWS = (IRasterWorkspace)wsFactory.OpenFromFile(folder, 0);
                IRasterDataset rasterDataset = rasterWS.OpenRasterDataset(name);
                return rasterDataset.CreateDefaultRaster();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载栅格失败: {ex.Message}");
                return null;
            }
        }

        private string GetPythonPath()
        {
            string knownGoodPython = @"D:\anaconda\anacanda\python.exe";

            if (File.Exists(knownGoodPython))
            {
                return knownGoodPython;  // 直接返回，跳过验证
            }

            MessageBox.Show(
                "未找到有效的 Python 执行路径。\n请检查 D:\\anconda\\python.exe 是否存在。",
                "Python 配置错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

            return null;
        }




        // 修正的热力图渲染方法
        private IRasterLayer RenderAsHeatmap(IRaster raster)
        {
            try
            {
                IRasterLayer rasterLayer = new RasterLayerClass();
                rasterLayer.CreateFromRaster(raster);

                // 创建拉伸渲染器
                IRasterStretchColorRampRenderer stretchRenderer = new RasterStretchColorRampRendererClass();
                stretchRenderer.BandIndex = 0;

                // 设置拉伸类型
                IRasterStretch2 stretch2 = (IRasterStretch2)stretchRenderer;
                stretch2.StretchType = esriRasterStretchTypesEnum.esriRasterStretch_StandardDeviations;

                // 创建色带
                IAlgorithmicColorRamp colorRamp = new AlgorithmicColorRampClass();
                colorRamp.FromColor = CreateRgbColor(0, 0, 255);
                colorRamp.ToColor = CreateRgbColor(255, 0, 0);
                colorRamp.Size = 256;
                colorRamp.CreateRamp(out bool _);

                stretchRenderer.ColorRamp = colorRamp;
                rasterLayer.Renderer = (IRasterRenderer)stretchRenderer;

                // 强制更新渲染
                IRasterRenderer renderer = (IRasterRenderer)stretchRenderer;
                renderer.Raster = raster;
                renderer.Update();

                return rasterLayer;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"渲染热力图失败: {ex.Message}");
                return null;
            }
        }

        private IRgbColor CreateRgbColor(int r, int g, int b)
        {
            IRgbColor color = new RgbColorClass();
            color.Red = r;
            color.Green = g;
            color.Blue = b;
            color.UseWindowsDithering = false;
            return color;
        }

        //其他辅助方法保持不变
        private IFeatureLayer GetLayerByName(string layerName)
        {
            for (int i = 0; i < axMapControl1.Map.LayerCount; i++)
            {
                ILayer layer = axMapControl1.Map.get_Layer(i);
                if (layer is IFeatureLayer && layer.Name == layerName)
                {
                    return (IFeatureLayer)layer;
                }
            }
            return null;
        }

        private void LoadNumericFieldsToComboBox(IFeatureLayer layer)
        {
            cmbPollutant.Items.Clear();

            if (layer == null || layer.FeatureClass == null)
            {
                MessageBox.Show("图层无效或尚未加载。");
                return;
            }

            IFields fields = layer.FeatureClass.Fields;
            for (int i = 0; i < fields.FieldCount; i++)
            {
                IField field = fields.get_Field(i);

                if (field.Type == esriFieldType.esriFieldTypeDouble ||
                    field.Type == esriFieldType.esriFieldTypeSingle ||
                    field.Type == esriFieldType.esriFieldTypeInteger ||
                    field.Type == esriFieldType.esriFieldTypeSmallInteger)
                {
                    cmbPollutant.Items.Add(field.Name);
                }
            }

            if (cmbPollutant.Items.Count > 0)
            {
                cmbPollutant.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("未找到可用于插值的数值字段！");
            }
        }

        private void 保存ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            // 查找所有可能的渲染结果图层
            List<IRasterLayer> renderLayers = new List<IRasterLayer>();

            for (int i = 0; i < axMapControl1.Map.LayerCount; i++)
            {
                ILayer layer = axMapControl1.Map.get_Layer(i);

                // 放宽条件，查找所有栅格图层
                if (layer is IRasterLayer rasterLayer)
                {
                    // 可以添加更多条件筛选特定图层
                    renderLayers.Add(rasterLayer);
                }
            }

            if (renderLayers.Count == 0)
            {
                MessageBox.Show("当前地图中没有找到任何栅格图层！\n请先生成热力图或渲染结果。");
                return;
            }

            // 让用户选择要保存的图层
            using (var form = new SaveForm(renderLayers))
            {
                if (form.ShowDialog() == DialogResult.OK && form.SelectedLayer != null)
                {
                    SaveFileDialog saveDialog = new SaveFileDialog
                    {
                        Filter = "TIFF 文件|*.tif|所有文件|*.*",
                        Title = "保存渲染结果",
                        OverwritePrompt = true
                    };

                    if (saveDialog.ShowDialog() == DialogResult.OK)
                    {
                        SaveRasterLayer(form.SelectedLayer, saveDialog.FileName);
                    }
                }
            }
        }

        private void SaveRasterLayer(IRasterLayer layer, string outputPath)
        {
            try
            {
                // 方法1：尝试通过IRasterLayer直接获取
                IRasterDataset rasterDataset = GetRasterDatasetFromLayer(layer);

                // 方法2：如果失败，尝试通过IRaster获取
                if (rasterDataset == null && layer.Raster != null)
                {
                    rasterDataset = GetRasterDatasetFromRaster(layer.Raster);
                }

                // 方法3：作为最后手段，尝试保存临时文件
                if (rasterDataset == null)
                {
                    string tempPath = Path.Combine(Path.GetTempPath(), "temp_raster.tif");
                    SaveRasterToTemp(layer, tempPath);
                    rasterDataset = OpenRasterDataset(tempPath);
                }

                if (rasterDataset == null)
                {
                    MessageBox.Show("无法获取栅格数据集！尝试了多种方法均失败。");
                    return;
                }

                // 创建工作空间
                IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
                IWorkspace workspace = workspaceFactory.OpenFromFile(Path.GetDirectoryName(outputPath), 0);

                // 保存为TIFF
                string fileName = Path.GetFileNameWithoutExtension(outputPath);
                rasterDataset.Copy(fileName, workspace);

                MessageBox.Show($"图层 '{layer.Name}' 已成功保存到:\n{outputPath}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}\n\n堆栈跟踪：{ex.StackTrace}");
            }
        }

        private IRasterDataset GetRasterDatasetFromLayer(IRasterLayer layer)
        {
            try
            {
                // 方法1：通过IDataset接口
                if (layer is IDataset dataset)
                {
                    return dataset as IRasterDataset;
                }

                // 方法2：通过Raster属性
                if (layer.Raster is IRasterDataset rasterDataset)
                {
                    return rasterDataset;
                }

                // 方法3：通过RasterBandCollection
                if (layer.Raster is IRasterBandCollection bandCollection && bandCollection.Count > 0)
                {
                    return bandCollection.Item(0).RasterDataset;
                }

                return null;
            }
            catch
            {
                return null;
            }
        }
        private bool TrySaveWithRasterDataset(IRaster raster, string workspacePath, string fileName)
        {
            try
            {
                // 获取栅格数据集
                IRasterDataset rasterDataset = GetRasterDatasetFromRaster(raster);
                if (rasterDataset == null) return false;

                // 创建工作空间
                IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
                IWorkspace workspace = workspaceFactory.OpenFromFile(workspacePath, 0);

                // 保存为TIFF
                rasterDataset.Copy(fileName, workspace);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private bool TrySaveWithConversion(IRaster raster, string outputPath)
        {
            try
            {
                // 创建工作空间
                IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
                IWorkspace workspace = workspaceFactory.OpenFromFile(Path.GetDirectoryName(outputPath), 0);

                // 创建转换操作
                IConversionOp conversionOp = new RasterConversionOpClass();
                IRasterAnalysisEnvironment env = (IRasterAnalysisEnvironment)conversionOp;
                env.OutWorkspace = workspace;

                // 转换为栅格数据集
                conversionOp.ToRasterDataset(
                    (IGeoDataset)raster,  // 显式转换为IGeoDataset
                    "TIFF",
                    workspace,
                    Path.GetFileNameWithoutExtension(outputPath));

                return true;
            }
            catch
            {
                return false;
            }
        }

        private IRasterDataset GetRasterDatasetFromRaster(IRaster raster)
        {
            try
            {
                // 方法1：直接转换
                if (raster is IRasterDataset dataset)
                {
                    return dataset;
                }

                // 方法2：通过RasterBandCollection获取
                if (raster is IRasterBandCollection bandCollection && bandCollection.Count > 0)
                {
                    return bandCollection.Item(0).RasterDataset;
                }

                return null;
            }
            catch
            {
                return null;
            }
        }

        private void 分级绘制图层ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DrawStationsForm form = new DrawStationsForm(axMapControl1);
            form.ShowDialog();
        }

        private void 取消分级显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IGraphicsContainer graphicsContainer = axMapControl1.ActiveView.GraphicsContainer;
            graphicsContainer.DeleteAllElements();
            axMapControl1.ActiveView.Refresh();
        }
    }
}